﻿<%@ Page Title="" ClientIDMode="Static" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ManageConnectionStrings.aspx.cs" Inherits="ConnStrMgmt.ManageConnectionStrings" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">
        $(function () {
            //get the user's connection strings for the first time
            GetConnectionStrings();

            //default to "add a connection string" mode
            addMode();

            //bind the callback for testing a connection's string connection
            $('#TestConnStrButton').click(function (e) {
                testConnection();

                //prevent unnecessary post back
                e.preventDefault();
            });

            //on change handler for databaseTypeName
            $('#DatabaseTypeName').change(function () {
                databaseTypeChange();
            });

            //jquery validation
            $("#Form1").validate();

            //initialize the page to show the appropriate fields
            //based on the database type
            databaseTypeChange();
        });

        //get the existing connection strings for the user
        function GetConnectionStrings() {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '<%= ResolveUrl("~/User/ManageConnectionStrings.aspx/GetConnectionStrings")%>',
                success:
                    function (data) {
                        var existingConnStrDiv = $('div#ConnStrExistingConnections');
                        existingConnStrDiv.html('');

                        var resp = eval(data.d);

                        if (resp.length > 0) {
                            var record = '';
                            var x = 1;
                            var manageConnStrDivId = '';

                            $.each(resp, function () {
                                manageConnStrDivId = 'manageConnStr' + x;

                                record +=
                                    '<div id="' + manageConnStrDivId + '" style="width: 350px">' +
                                        '<div style="width: 250px; float: left;">' +
                                            this.connStrName + ' [' + this.connStrServer + ']' +
                                        '</div>' +
                                        '<div style="margin-left: 10px; float: left;">' +
                                            '<img style="cursor: hand; cursor: pointer" onclick="editConnection(\'' + this.connStrName + '\', \'' + this.databaseTypeName + '\')" alt="edit" src=<%= ResolveUrl("~/img/editicon.png") %> />' +
                                        '</div>' +
                                        '<div style="margin-left: 10px; float: left;">' +
                                            '<img style="cursor: hand; cursor: pointer" onclick="deleteConnection(\'' + this.connStrName + '\', \'' + this.databaseTypeName + '\')" alt="delete" src=<%= ResolveUrl("~/img/deleteicon.png") %> />' +
                                        '</div>' +
                                    '</div>';

                                x++;
                            });

                            existingConnStrDiv.html(record);
                        }
                        else {
                            existingConnStrDiv.html('No connections found.');
                        }
                    },
                error:
                    function (data) {
                        alert("failed!")
                    }
            });
        }

        //switch to add mode
        function addMode() {
            $('div.ConnStrHeader').html('<h3>Add Connection String</h3><p>Add a new connection string below.</p>');
            $('input#AddConnStrSubmit').show();
            $('input#EditConnStrSubmit').hide();

            //clear all the fields
            resetFields();

            //set the fields based on the database type
            databaseTypeChange();
        }

        //switch to edit mode
        function editMode() {
            $('div.ConnStrHeader').html('<h3>Edit Connection String</h3><p>Edit the existing connection string. <span onclick="addMode()" style="color: blue; text-decoration: underline; cursor: hand; cursor: pointer">Switch to Add Mode</span></p>');
            $('input#AddConnStrSubmit').hide();
            $('input#EditConnStrSubmit').show();
        }

        //resets the fields
        function resetFields() {
            $('#ConnStrName').val('');
            $('#DatabaseTypeName').val('');
            $('#ConnStrUserName').val('');
            $('#ConnStrPassword').val('');
            $('#ConnStrServer').val('');
            $('#ConnStrPort').val('');
            $('#ConnStrServiceName').val('');
            $('#ConnStrDatabaseName').val('');

            $('#OriginalConnStrName').val('');
            $('#OriginalDatabaseTypeName').val('');
        }

        //sets the form up to edit the connection
        function editConnection(connStrName, databaseTypeName) {
            //edit the labels
            editMode();

            //get the data
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '<%= ResolveUrl("~/User/ManageConnectionStrings.aspx/GetConnectionString") %>',
                data: { 'connStrName': '\'' + connStrName + '\'', 'databasetypeName': '\'' + databaseTypeName + '\'' },
                success:
                    function (data) {
                        //populate form fields
                        var resp = eval(data.d);

                        $('#ConnStrName').val(resp.connStrName);
                        $('#DatabaseTypeName').val(resp.databaseTypeName);
                        $('#ConnStrUserName').val(resp.connStrUserName);
                        $('#ConnStrPassword').val(resp.connStrPassword);
                        $('#ConnStrServer').val(resp.connStrServer);
                        $('#ConnStrPort').val(resp.connStrPort);
                        $('#ConnStrServiceName').val(resp.connStrServiceName);
                        $('#ConnStrDatabaseName').val(resp.connStrDatabaseName);

                        $('#OriginalConnStrName').val(resp.connStrName);
                        $('#OriginalDatabaseTypeName').val(resp.databaseTypeName);

                        //set the fields
                        databaseTypeChange();
                    },
                error:
                    function () {
                        alert("Get Connection String Error!");
                    }
            });

        }

        //deletes the connection string
        function deleteConnection(connStrName, databaseTypeName) {
            if (confirm("Are you sure you wish to delete this?")) {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: '<%= ResolveUrl("~/User/ManageConnectionStrings.aspx/DeleteConnectionString")%>',
                    data: JSON.stringify({ connStrName: connStrName, databaseTypeName: databaseTypeName }),
                    success:
                        function () {
                            GetConnectionStrings();
                        },
                    error:
                        function () {
                            alert("delete failed!");
                        }
                });
            }
        }

        //switches the fields based on the database type
        function databaseTypeChange() {
            //get all fields
            var connStrName = $('#ConnStrName'); //always shown
            var databaseTypeName = $('#DatabaseTypeName'); //always shown
            var connStrUserName = $('div#ConnStrUserNameField');
            var connStrPassword = $('div#ConnStrPasswordField');
            var connStrServer = $('div#ConnStrServerField');
            var connStrPort = $('div#ConnStrPortField');
            var connStrServiceName = $('div#ConnStrServiceNameField');
            var connStrDatabaseName = $('div#ConnStrDatabaseNameField');

            if ($('#DatabaseTypeName option:selected').text() == 'MS Access') {
                //show MS Access fields
                connStrServer.show();
                connStrPassword.show();

                //hide non-MS Access fields
                connStrUserName.hide();
                connStrPort.hide();
                connStrServiceName.hide();
                connStrDatabaseName.hide();

                //clear the hidden fields
                $('#ConnStrUserName').val('');
                $('#ConnStrPort').val('');
                $('#ConnStrServiceName').val('');
                $('#ConnStrDatabaseName').val('');
            }
            else if ($('#DatabaseTypeName option:selected').text() == 'Oracle') {
                //show Oracle fields
                connStrUserName.show();
                connStrPassword.show();
                connStrServer.show();
                connStrPort.show();
                connStrServiceName.show();

                //hide non-Oracle fields
                connStrDatabaseName.hide();

                //clear the hidden field
                $('#ConnStrDatabaseName').val('');
            }
            else if ($('#DatabaseTypeName option:selected').text() == 'SQL Server') {
                //show SQL Server fields
                connStrUserName.show();
                connStrPassword.show();
                connStrServer.show();
                connStrDatabaseName.show();

                //hide non-SQL Server fields
                connStrServiceName.hide();
                connStrPort.hide();

                //clear the hidden fields
                $('#ConnStrServiceName').val('');
            }
        }

        //tests the connection
        function testConnection() {
            $('#TestConnStrButton').html('Testing...');

            var connStrName = $('#ConnStrName').val();
            var databaseTypeName = $('#DatabaseTypeName').val();
            var connStrUserName = $('#ConnStrUserName').val();
            var connStrPassword = $('#ConnStrPassword').val();
            var connStrServer = $('#ConnStrServer').val();
            var connStrPort = $('#ConnStrPort').val();
            var connStrServiceName = $('#ConnStrServiceName').val();
            var connStrDatabaseName = $('#ConnStrDatabaseName').val();

            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '<%= ResolveUrl("~/User/ManageConnectionStrings.aspx/TestConnectionString") %>',
                data: {
                    'connStrName': '\'' + connStrName + '\'', 'databaseTypeName': '\'' + databaseTypeName + '\'',
                    'connStrUserName': '\'' + connStrUserName + '\'', 'connStrPassword': '\'' + connStrPassword + '\'',
                    'connStrServer': '\'' + connStrServer + '\'', 'connStrPort': '\'' + connStrPort + '\'',
                    'connStrServiceName': '\'' + connStrServiceName + '\'', 'connStrDatabaseName': '\'' + connStrDatabaseName + '\''
                },
                success:
                    function (data) {
                        if (data.d) {
                            alert("Test succeeded!");
                        }
                        else {
                            alert("Test failed!");
                        }

                        $('#TestConnStrButton').html('Test Connection');
                    },
                error:
                    function () {
                        alert("Test failed!");
                        $('#TestConnStrButton').html('Test Connection');
                    }
            });
        }
    </script>

    <style type="text/css">
        .error {
            color: red;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div id="ConnStrStatusContainer">
        <asp:Label ID="ConnStrStatus" Visible = "false" runat="server" />
    </div>

    <div class="ConnStrMgmtContainer" style="width: 900px; height: 100%; margin-bottom: 15px">
        <div id="ConnStrMgmtHeader">
            <h2>Manage Connection Strings</h2>
        </div>
        <div class="AddConnStrContainer" style="float: left; width: 500px">
            <div class="ConnStrHeader">
                <p>Add Connection String</p>
            </div>
            <div id="ConnStrNameField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Connection String Name
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrName" CssClass="required" runat="server"></asp:TextBox>
                </div>
            </div>

            <div id="DatabaseTypeNameField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Database Type Name
                </div>
                <div class="ConnStrFieldValue">
                    <asp:DropDownList ID="DatabaseTypeName" runat="server"></asp:DropDownList>
                </div>
            </div>

            <div id="ConnStrUserNameField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    User Name
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrUserName" CssClass="required" runat="server"></asp:TextBox>
                </div>
            </div>
        
            <div id="ConnStrPasswordField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Password
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrPassword" CssClass="required" runat="server" TextMode="Password"></asp:TextBox>
                </div>
            </div>
        
            <div id="ConnStrServerField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Database Server
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrServer" CssClass="required" runat="server"></asp:TextBox>
                </div>
            </div>

            <div id="ConnStrPortField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Database Server Port
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrPort" CssClass="required digits" runat="server"></asp:TextBox>
                </div>
            </div>
        
            <div id="ConnStrServiceNameField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Service Name
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrServiceName" CssClass="required" runat="server"></asp:TextBox>
                </div>
            </div>
        
            <div id="ConnStrDatabaseNameField" class="ConnStrField">
                <div class="ConnStrFieldLabel">
                    Database Name
                </div>
                <div class="ConnStrFieldValue">
                    <asp:TextBox ID="ConnStrDatabaseName" CssClass="required" runat="server"></asp:TextBox>
                </div>
            </div>
            <asp:TextBox ID="OriginalConnStrName" style="display: none;" runat="server" />
            <asp:TextBox ID="OriginalDatabaseTypeName" style="display: none;" runat="server" />
            <div id="ButtonContainer" style="margin-bottom:  10px; margin-top:  10px">
                <asp:Button ID="AddConnStrSubmit" Text="Add String" runat="server" 
                    onclick="AddConnStrSubmit_Click" />
                <asp:Button ID="EditConnStrSubmit" Text="Edit String" runat="server" 
                    onclick="EditConnStrSubmit_Click" />
                <button id="TestConnStrButton">Test Connection</button>
            </div>
        </div>

        <div class="ConnStrExistingConnectionsContainer" style="width: 390px; margin-left: 510px">
            <div class="ConnStrExistingConnectionsHeader" style="border-bottom: 1px solid grey; margin-bottom: 5px">
                <h3>Existing Connections</h3>
                <p>Your existing connections are show below.</p>
            </div>
            <div id="ConnStrExistingConnections">
            </div>
        </div>
    </div>
</asp:Content>
